package com.rdxy.common.utils;

import com.alibaba.fastjson2.JSON;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;
import javax.net.ssl.SSLException;
public class FaceUtil {

    private static String API_KEY="CdrqOEYVo9IUHIA2lue5wuv-361vPVlo";
    private static String API_SECRET="WiY7_w9Ukm-TsTBUZVtxEKDpZ35hTIbq";

    private static String FACESET_TOKEN="8d199dd7d10c1b0464782d66e5ff2ccc";


    public static String face(String imageBase64_1) throws IOException {

        return face(imageBase64_1,imageBase64_1);
    }

    public static String search(String imageBase64) throws IOException{

        String url = "https://api-cn.faceplusplus.com/facepp/v3/search";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> byteMap = new HashMap<>();
        map.put("api_key", API_KEY);
        map.put("api_secret", API_SECRET);
        map.put("return_landmark", "1");
        map.put("faceset_token",FACESET_TOKEN);
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_image_base64",imageBase64);

        String str=null;
        try{
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
            System.out.println(str);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return str;

    }

    public static String face(String imageBase64_1,String face_token) throws IOException{
        byte[] buff1 = getStringImage(imageBase64_1.substring(imageBase64_1.indexOf(",")+1));

        String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> byteMap = new HashMap<>();
        map.put("api_key", API_KEY);
        map.put("api_secret", API_SECRET);
        map.put("return_landmark", "1");
        map.put("face_token2",face_token);
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file1", buff1);


        String str=null;
        try{
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
            System.out.println(str);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return str;

    }

//    public static String face(String imageBase64_1,String imageBase64_2) throws IOException{
//        byte[] buff1 = getStringImage(imageBase64_1.substring(imageBase64_1.indexOf(",")+1));
//        byte[] buff2 = getStringImage(imageBase64_2.substring(imageBase64_2.indexOf(",")+1));
//
//        String url = "https://api-cn.faceplusplus.com/facepp/v3/compare";
//        HashMap<String, String> map = new HashMap<>();
//        HashMap<String, Object> byteMap = new HashMap<>();
//        map.put("api_key", API_KEY);
//        map.put("api_secret", API_SECRET);
//        map.put("return_landmark", "1");
//        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
//        byteMap.put("image_file1", buff1);
//        byteMap.put("image_file2", buff2);
//
//        String str=null;
//        try{
//            byte[] bacd = post(url, map, byteMap);
//            str = new String(bacd);
//            System.out.println(str);
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        return str;
//
//    }

    public static byte[] getStringImage(String base64String) throws IOException {
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        return base64String != null ? decoder.decodeBuffer(base64String) : null;
    }


    private final static int CONNECT_TIME_OUT = 30000;
    private final static int READ_OUT_TIME = 50000;
    private static String boundaryString = getBoundary();
    protected static byte[] post(String url, HashMap<String, String> map, HashMap<String, Object> fileMap) throws Exception {
        HttpURLConnection conne;
        URL url1 = new URL(url);
        conne = (HttpURLConnection) url1.openConnection();
        conne.setDoOutput(true);
        conne.setUseCaches(false);
        conne.setRequestMethod("POST");
        conne.setConnectTimeout(CONNECT_TIME_OUT);
        conne.setReadTimeout(READ_OUT_TIME);
        conne.setRequestProperty("accept", "*/*");
        conne.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
        conne.setRequestProperty("connection", "Keep-Alive");
        conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
        DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
        Iterator iter = map.entrySet().iterator();
        while(iter.hasNext()){
            Map.Entry<String, String> entry = (Map.Entry) iter.next();
            String key = entry.getKey();
            String value = entry.getValue();
            obos.writeBytes("--" + boundaryString + "\r\n");
            obos.writeBytes("Content-Disposition: form-data; name=\"" + key
                    + "\"\r\n");
            obos.writeBytes("\r\n");
            obos.writeBytes(value + "\r\n");
        }
        if(fileMap != null && fileMap.size() > 0){
            Iterator fileIter = fileMap.entrySet().iterator();
            while(fileIter.hasNext()){
                Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
                obos.writeBytes("--" + boundaryString + "\r\n");
                obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
                        + "\"; filename=\"" + encode(" ") + "\"\r\n");
                obos.writeBytes("\r\n");
                obos.write(fileEntry.getValue());
                obos.writeBytes("\r\n");
            }
        }
        obos.writeBytes("--" + boundaryString + "--" + "\r\n");
        obos.writeBytes("\r\n");
        obos.flush();
        obos.close();
        InputStream ins = null;
        int code = conne.getResponseCode();
        try{
            if(code == 200){
                ins = conne.getInputStream();
            }else{
                ins = conne.getErrorStream();
            }
        }catch (SSLException e){
            e.printStackTrace();
            return new byte[0];
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[4096];
        int len;
        while((len = ins.read(buff)) != -1){
            baos.write(buff, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        ins.close();
        return bytes;
    }
    private static String getBoundary() {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i = 0; i < 32; ++i) {
            sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
        }
        return sb.toString();
    }
    private static String encode(String value) throws Exception{
        return URLEncoder.encode(value, "UTF-8");
    }

    public static String create(String face_tokens){

        return null;
    }

    public static String detect(String imageBase64_1) throws IOException {
        String url="https://api-cn.faceplusplus.com/facepp/v3/detect";
        byte[] buff1 = getStringImage(imageBase64_1.substring(imageBase64_1.indexOf(",")+1));

        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> byteMap = new HashMap<>();
        map.put("api_key", API_KEY);
        map.put("api_secret", API_SECRET);
        map.put("return_landmark", "1");
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
        byteMap.put("image_file", buff1);

        String str=null;
        try{
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
//            System.out.println(str);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    public static String addFace(String face_token) throws IOException {
        String url="https://api-cn.faceplusplus.com/facepp/v3/faceset/addface";

        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> byteMap = new HashMap<>();
        map.put("api_key", API_KEY);
        map.put("api_secret", API_SECRET);
        map.put("faceset_token",FACESET_TOKEN);
        map.put("return_landmark", "1");
        map.put("face_tokens",face_token);
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
//        byteMap.put("face_tokens", face_token);

        String str=null;
        try{
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
            System.out.println(str);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return str;
    }

    public static boolean removeFace(String face_token) throws IOException {
        String url=" https://api-cn.faceplusplus.com/facepp/v3/faceset/removeface";

        HashMap<String, String> map = new HashMap<>();
        HashMap<String, Object> byteMap = new HashMap<>();
        map.put("api_key", API_KEY);
        map.put("api_secret", API_SECRET);
        map.put("faceset_token",FACESET_TOKEN);
        map.put("return_landmark", "1");
        map.put("face_tokens",face_token);
        map.put("return_attributes", "gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus");
//        byteMap.put("face_tokens", face_token);

        String str=null;
        try{
            byte[] bacd = post(url, map, byteMap);
            str = new String(bacd);
            System.out.println(str);
        }catch (Exception e) {
            e.printStackTrace();
        }

        Object face_count = JSON.parseObject(str).get("face_removed");
        return face_count!=null;
    }

}
